package frank.zou.study.testng.extending.ScheduledTestSample;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.testng.IMethodSelector;
import org.testng.IMethodSelectorContext;
import org.testng.ITestNGMethod;

public class ScheduledTestSelector implements IMethodSelector {

	public boolean includeMethod(IMethodSelectorContext context,
			ITestNGMethod testNgMethod, boolean isTestMethod) {

		Method method = testNgMethod.getMethod();
		Annotation annotation = method.getAnnotation(ScheduledTest.class);
		if (annotation != null) { 
			Date now = Calendar.getInstance().getTime();
			ScheduledTest scheduledTestAnnotation = (ScheduledTest) annotation;
			Date activeAfter = null; 
			String activeAfterStirng = scheduledTestAnnotation.activeAfter();
			if (activeAfterStirng != null && 
					! "".equals(activeAfterStirng)) { 
				activeAfter = parseDate(activeAfterStirng);
				// only include this method if now is after the specified date
				if (now.before(activeAfter)) { 
					return false;
				}
			}
		}
		
		return true;
		
	}

	private Date parseDate(String activeAfterStirng) {
		SimpleDateFormat formatter =
			new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try {
				return formatter.parse(activeAfterStirng);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
	}

	public void setTestMethods(List<ITestNGMethod> arg0) {
		// TODO Auto-generated method stub

	}

}
